package org.dromara.common.tenant.manager

import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper
import io.github.oshai.kotlinlogging.KotlinLogging
import org.dromara.common.core.constant.GlobalConstants
import org.dromara.common.core.utils.StringUtils
import org.dromara.common.redis.manager.PlusSpringCacheManager
import org.dromara.common.tenant.helper.TenantHelper.getTenantId
import org.springframework.cache.Cache

/**
 * 重写 cacheName 处理方法 支持多租户
 *
 * @author LikeYouDo
 * @date 2025/07/26
 */
class TenantSpringCacheManager: PlusSpringCacheManager() {
    companion object{
        private val log = KotlinLogging.logger {  }
    }

    override fun getCache(name: String): Cache? {
        if (InterceptorIgnoreHelper.willIgnoreTenantLine("")) {
            return super.getCache(name)
        }
        if (StringUtils.contains(name, GlobalConstants.GLOBAL_REDIS_KEY)) {
            return super.getCache(name)
        }
        val tenantId = getTenantId()
        if (StringUtils.isBlank(tenantId)) {
            error { "无法获取有效的租户id -> Null" }
        }
        if (StringUtils.startsWith(name, tenantId)) {
            // 如果存在则直接返回
            return super.getCache(name)
        }
        return super.getCache("$tenantId:$name")
    }
}
